package mi.payment.db;

import android.database.sqlite.SQLiteDatabase;

import org.greenrobot.greendao.identityscope.IdentityScopeType;
import org.greenrobot.greendao.query.QueryBuilder;

import java.text.SimpleDateFormat;
import java.util.Date;

import mi.payment.constants.Params;
import mi.payment.db.dao.DBManager;
import mi.payment.db.dao.DaoMaster;
import mi.payment.db.dao.DaoSession;
import mi.payment.db.dao.PaySettlement;
import mi.payment.db.dao.PaySettlementDao;


public class SettlementModel {

    private PaySettlementDao mPaySettlementDao;

    private static SettlementModel instance;

    private SettlementModel() {
        SQLiteDatabase database = DBManager.getInstance().getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(database);
        DaoSession daoSession = daoMaster.newSession(IdentityScopeType.None);
        mPaySettlementDao = daoSession.getPaySettlementDao();
    }

    public static SettlementModel getInstance() {
        if (instance == null) {
            instance = new SettlementModel();
        }
        return instance;
    }

    public void insertByBatchNo(String batchNo) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm" + "ss");
        Date date = new Date();
        String cdt = dateFormat.format(date);
        PaySettlement settlement = new PaySettlement();
        settlement.TransBatchNo = batchNo;
        if (Params.userInfo != null) {
            settlement.Operator = Params.userInfo.getUId();
        } else {
            settlement.Operator = "01";
        }
        settlement.LocalDate = cdt;
        settlement.LocalTime = cdt;
        insert(settlement);
    }

    /**
     * 清空表数据
     */
    public void emptyTableData() {
        mPaySettlementDao.deleteAll();
    }

    /**
     * 查询表中有多少条记录
     */
    public int getRowCount() {
        QueryBuilder<PaySettlement> qb = mPaySettlementDao.queryBuilder();
        return qb.build().list().size();
    }

    /**
     * 根据批次号获取一条PaySettlement数据
     */
    public PaySettlement getPaySettlementByBatchNo(String batchNo) {
        QueryBuilder<PaySettlement> qb = mPaySettlementDao.queryBuilder();
        qb.where(
                PaySettlementDao.Properties.TransBatchNo.eq(batchNo)
        );
        return qb.build().unique();
    }

    public void insert(PaySettlement ps) {
        mPaySettlementDao.insert(ps);
    }

    public void update(PaySettlement ps) {
        if (ps != null) {
            mPaySettlementDao.update(ps);
        }
    }

}
